<template>
	<view class="coupon-center-container page-container">
		<!-- 顶部横幅 -->
		<view class="banner-section">
			<text class="banner-text">🎫 精选优惠券，助您省钱购好茶</text>
		</view>

		<!-- 优惠券分类 -->
		<view class="category-tabs">
			<view class="category-tab" v-for="(category, index) in categories" :key="index"
				:class="{ active: activeCategory === index }" @click="switchCategory(index)">
				<text class="tab-text">{{ category.name }}</text>
			</view>
		</view>

		<!-- 优惠券列表 -->
		<view class="coupon-list">
			<view class="coupon-card" v-for="(coupon, index) in couponsList" :key="index"
				:class="{ received: !canReceiveCoupon(coupon), expired: coupon.coupon_status===3 }">
				<view class="coupon-left">
					<view v-if="coupon.content_type===3" class="coupon-amount">
						<text class="amount-value">{{ coupon.discount }}</text>
						<text class="amount-symbol">折</text>
					</view>
					<view v-else class="coupon-amount">
						<text class="amount-symbol">¥</text>
						<text class="amount-value">{{ coupon.coupon_amount }}</text>
					</view>
					<text v-if="coupon.content_type===1" class="coupon-condition">满 {{ coupon.threshold }} 元可用</text>
				</view>
				<view class="coupon-right">
					<view class="coupon-info">
						<text class="coupon-name">{{ coupon.coupon_name }}</text>
						<text class="coupon-desc">{{ coupon.coupon_scene }}</text>
						<view class="coupon-time">
							<text v-if="coupon.coupon_validity_type===1"
								class="time-text">有效期：{{ $tools.yyyymmddFormat(coupon.coupon_end_time) }}</text>
							<text v-else class="time-text">有效期：{{ getPeriod(coupon.coupon_valid_period) }}</text>
						</view>
					</view>
					<view class="coupon-action">
						<button class="receive-btn" :class="{ 
								received: !canReceiveCoupon(coupon),
								disabled: coupon.available_num === 0 
							}" @click="receiveCoupon(coupon, index)" :disabled="!canReceiveCoupon(coupon)">
							{{ getButtonText(coupon) }}
						</button>
						<text v-if="coupon.available_num" class="stock-text">
							剩余 {{ coupon.available_num }} 张
						</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view v-if="couponsList.length === 0" class="empty-state">
			<image src="@/static/images/empty-coupon.png" mode="aspectFit" class="empty-image"></image>
			<text class="empty-text">暂无可领取的优惠券</text>
		</view>

		<!-- 领取成功弹窗 -->
		<view v-if="showSuccessModal" class="success-modal" @click="showSuccessModal = false">
			<view class="modal-content" @click.stop>
				<view class="success-icon">🎉</view>
				<text class="success-title">领取成功！</text>
				<text class="success-desc">优惠券已放入您的卡包</text>
				<button class="modal-btn" @click="showSuccessModal = false">确定</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				activeCategory: 0,
				showSuccessModal: false,
				hasSearched: false,
				recordCount: 0,
				page: 1,
				limit: 10,
				couponsList: [], // 当前显示的优惠券列表
				// 优惠内容（1:满减券 2:直减券 3:折扣券）
				categories: [{
						name: '全部',
						type: 0
					},
					{
						name: '新人专享',
						type: 10
					},
					{
						name: '满减券',
						type: 1
					},
					{
						name: '直减券',
						type: 2
					},
					{
						name: '折扣券',
						type: 3
					}
				],
				recvCondition: {
					isNewUser: false,
					isComment: false,
					isBirthday: false
				}
			}
		},
		onLoad(options) {
			this.loadUserRecvCondition();
			this.onSearch();
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {
			if (!this.hasSearched) {
				this.page = 1
				this.recordCount = 0
				this.couponsList = []
				this.loadDataList()
			}
		},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {
			// 下拉触底，先判断是否有请求正在进行中
			// 以及检查当前请求页数是不是小于数据总页数，如符合条件，则发送请求
			const page = this.page
			const limit = this.limit
			const recordCount = this.recordCount
			if (!this.hasSearched && page * limit < recordCount) {
				this.page++
				setTimeout(() => {
					this.loadDataList()
				}, 500)
			}
		},
		methods: {
			// 重新重新事件
			onSearch() {
				this.page = 1
				this.recordCount = 0
				this.couponsList = []
				this.loadDataList()
			},
			loadDataList() {
				// 加载数据列表
				if (this.hasSearched) {
					return false
				}

				this.hasSearched = true
				this.$api.coupon.GetCouponList({
					page: this.page,
					limit: this.limit,
					content_type: this.categories[this.activeCategory].type
				}).then(res => {
					this.hasSearched = false
					this.recordCount = res.count
					this.couponsList = this.couponsList.concat(res.data)
				}).catch(err => {
					this.hasSearched = false
					if (this.page > 0) {
						this.page--
					}
				})
			},

			loadUserRecvCondition() {
				// 加载用户领取资格
				this.$api.coupon.GetUserRecvCondition().then(res => {
					this.recvCondition = res.data
				})
			},

			// 切换分类
			switchCategory(index) {
				this.activeCategory = index
				this.onSearch()
			},

			// 领取优惠券
			receiveCoupon(coupon, index) {
				if (!this.canReceiveCoupon(coupon)) {
					return
				}

				uni.showLoading({
					title: '领取中...'
				})

				this.$api.coupon.ReceiveCoupon({
					coupon_id: coupon.id
				}).then(res => {
					uni.hideLoading()

					// 更新优惠券状态
					coupon.received++
					coupon.available_num = Math.max(0, coupon.available_num - 1)

					// 显示成功弹窗
					this.showSuccessModal = true

					// 触发震动反馈
					uni.vibrateShort()
				})
			},

			canReceiveCoupon(coupon) {
				if (coupon.received >= coupon.coupon_max_apply_times) return false;
				if (coupon.coupon_status !== 2) return false;
				if (coupon.available_num === 0) return false;
				if (coupon.coupon_type == 1 && !this.recvCondition.isNewUser) return false;
				if (coupon.coupon_type == 2 && this.recvCondition.isNewUser) return false;
				if (coupon.coupon_type == 3 && !this.recvCondition.isComment) return false;
				if (coupon.coupon_type == 4 && !this.recvCondition.isBirthday) return false;
				return true
			},

			getPeriod(seconds) {
				const days = Math.floor(seconds / (24 * 60 * 60));
				const hours = Math.floor((seconds % (24 * 60 * 60)) / (60 * 60));
				const minutes = Math.floor((seconds % (60 * 60)) / 60);
				if (days > 0) {
					return days + ' 天';
				} else if (hours > 0) {
					return hours + ' 小时';
				} else if (minutes > 0) {
					return minutes + ' 分钟';
				} else {
					seconds + ' 秒'
				}
			},

			// 获取按钮文字
			getButtonText(coupon) {
				if (coupon.coupon_status === 3) {
					return '已过期'
				}
				if (coupon.received >= coupon.coupon_max_apply_times) {
					return '已领取'
				}
				if (coupon.available_num === 0) {
					return '已抢完'
				}
				return '立即领取'
			}
		}
	}
</script>

<style lang="scss" scoped>
	.coupon-center-container {
		background-color: #f8f9fa;
	}

	/* 顶部横幅 */
	.banner-section {
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		padding: 30rpx;
		text-align: center;
	}

	.banner-text {
		color: white;
		font-size: 28rpx;
		font-weight: 500;
	}

	/* 分类标签 */
	.category-tabs {
		display: flex;
		background: white;
		padding: 0 30rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.category-tab {
		flex: 1;
		padding: 30rpx 0;
		text-align: center;
		position: relative;
	}

	.category-tab.active .tab-text {
		color: #52a58a;
		font-weight: bold;
	}

	.category-tab.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background-color: #52a58a;
		border-radius: 2rpx;
	}

	.tab-text {
		font-size: 28rpx;
		color: #666;
	}

	/* 优惠券列表 */
	.coupon-list {
		padding: 30rpx;
	}

	.coupon-card {
		background: white;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		padding: 30rpx;
		display: flex;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
		position: relative;
		overflow: hidden;
	}

	.coupon-card.received {
		opacity: 0.6;
	}

	.coupon-card.expired {
		opacity: 0.4;
		background: #f5f5f5;
	}

	.coupon-card::before {
		content: '';
		position: absolute;
		left: 200rpx;
		top: 0;
		bottom: 0;
		width: 2rpx;
		background: linear-gradient(to bottom, transparent 0%, #e5e5e5 20%, #e5e5e5 80%, transparent 100%);
	}

	/* 优惠券左侧 */
	.coupon-left {
		width: 200rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		margin: -30rpx 0 -30rpx -30rpx;
		border-radius: 20rpx 0 0 20rpx;
		color: white;
	}

	.coupon-amount {
		display: flex;
		align-items: baseline;
		margin-bottom: 8rpx;
	}

	.amount-symbol {
		font-size: 24rpx;
		margin-right: 4rpx;
	}

	.amount-value {
		font-size: 48rpx;
		font-weight: bold;
	}

	.coupon-condition {
		font-size: 22rpx;
		opacity: 0.9;
	}

	/* 优惠券右侧 */
	.coupon-right {
		flex: 1;
		padding-left: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.coupon-info {
		flex: 1;
	}

	.coupon-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 8rpx;
	}

	.coupon-desc {
		font-size: 24rpx;
		color: #666;
		display: block;
		margin-bottom: 12rpx;
	}

	.coupon-time {
		margin-bottom: 8rpx;
	}

	.time-text {
		font-size: 22rpx;
		color: #999;
	}

	/* 领取按钮 */
	.coupon-action {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 8rpx;
	}

	.receive-btn {
		width: 140rpx;
		height: 60rpx;
		border-radius: 30rpx;
		font-size: 24rpx;
		font-weight: bold;
		border: none;
		background: #52a58a;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.receive-btn.received,
	.receive-btn.expired,
	.receive-btn.disabled {
		background: #ccc;
		color: #999;
	}

	.stock-text {
		font-size: 20rpx;
		color: #999;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 30rpx;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
	}

	/* 成功弹窗 */
	.success-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
	}

	.modal-content {
		background: white;
		border-radius: 20rpx;
		padding: 60rpx 40rpx 40rpx;
		width: 500rpx;
		max-width: 80vw;
		text-align: center;
	}

	.success-icon {
		font-size: 80rpx;
		margin-bottom: 20rpx;
	}

	.success-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 16rpx;
	}

	.success-desc {
		font-size: 26rpx;
		color: #666;
		display: block;
		margin-bottom: 40rpx;
	}

	.modal-btn {
		width: 200rpx;
		height: 70rpx;
		background: #52a58a;
		color: white;
		border: none;
		border-radius: 35rpx;
		font-size: 28rpx;
		font-weight: bold;
	}
</style>